package icu.xuyijie.springbootlearning1.chapter3.mybatis;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @author 徐一杰
 * @date 2025/02/25 15:49
 * @description
 */
@RestController
@RequestMapping("/mybatis")
@Tag(name = "MMybatis相关操作")
public class MybatisController {

    @Autowired
    private MyEntityMapper myEntityMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/findAll")
    @Operation(summary = "查询全部", description = "详细描述，写不写无所谓")
    public void findAll() {
        // 开始时间
        long startTime = System.currentTimeMillis();

        // 判断缓存中是否有数据
        List findAllList = redisTemplate.opsForList().range("findAll", 0, -1);
        if (findAllList.size() > 0) {
            System.out.println(findAllList);
            System.out.println("查询耗时：" + (System.currentTimeMillis() - startTime) + "ms");
            // 缓存中有数据，直接return，后续的MySQL查询就不需要了
            return;
        }

        // 如果缓存中没数据，从MySQL查询
        List<MyEntity> all = myEntityMapper.findAll();
        System.out.println(all);
        long endTime = System.currentTimeMillis() - startTime;
        System.out.println("查询耗时：" + endTime + "ms");

        // 把MySQL查询的数据塞进缓存中，那么后续的查询就会直接取缓存，从而提高性能
        redisTemplate.opsForList().leftPush("findAll", all);
    }

    @GetMapping("/findOne")
    // 标记此方法允许跨域
    //@CrossOrigin
    @Operation(summary = "查询一个", description = "根据id查询一个信息")
    public MyEntity findOne(HttpSession session) {
        System.out.println(session.getId());
        MyEntity myEntity = myEntityMapper.findById(1);
        System.out.println(myEntity);
        return myEntity;
    }

    @GetMapping("/add")
    @Operation(summary = "新增一条")
    public void add() {
        MyEntity myEntity = new MyEntity();
        myEntity.setName("sadasd");
        myEntity.setCreateTime(new Date());
        myEntityMapper.insert(myEntity);
    }

    @GetMapping("/update")
    @Operation(summary = "更新一条", parameters = {
            @Parameter(name = "id", description = "要更新的数据主键"),
            @Parameter(name = "name", description = "要修改成的数据")
    })
    public void update(Integer id, String name) {
        myEntityMapper.update(name, id);
    }

    @GetMapping("/del")
    @Operation(summary = "删除一条")
    public void del() {
        myEntityMapper.delete(9);
    }

}
